%script to run PIV analysis for YR150827

%% 
pnseq='C:\Users\gracec\Documents\PICS DATA\Lab Tests December2016\Sequences_Pollen\';  %Path containing the SEQ files
pnout='C:\Users\gracec\Documents\PICS DATA\Lab Tests December2016\Sequences_Pollen\test_piv\'; %Path to write results
if ~exist(pnout,'file') %if output directory doesn't exist, create it
    mkdir(pnout);
end
files=dir(fullfile(pnseq,'*.seq')); %list of SEQ files for processing
nf=length(files); %number of files in the list
nstart=1; %starting index in the file list
%nf=25; %ending index of file list

for k=nstart:nf
   disp(['Starting file ' num2str(k) ' of ' num2str(nf)])
   fnseq=fullfile(pnseq,files(k).name);
   fnout=fullfile(pnout,['piv_',strrep(files(k).name,'.seq','.mat')]);
   hdr=load_SEQ(fnseq);
   fps=hdr.FrameRate;
   m=im_background(fnseq,'mode',50);
  % piv=im_piv_new(fnseq,m,[8,10],'bwrep');
  piv=im_piv_new(fnseq,[8,10],'bwrep');
   %% Check to see is using default Nthresh=5 is approcpriate.(This becomes important when there are low concentrations of small particles).
   %Added KAF May 2016
   Nthresh=5; %default value for Nthresh. Typically defined in im_piv_correct,but pulling it out here to do the check.
%    Nthresh_check=(sum(piv.N(:)>=Nthresh)/numel(piv.N));
%    piv_Nthresh=[Nthresh Nthresh_check];
%     if (sum(piv.N(:)>=Nthresh)/numel(piv.N))<0.5
%         while  Nthresh_check<0.5
%         choice=questdlg(['Less than 50% of particles match PIV critera with Nthresh = ',num2str(Nthresh),' Would you like to change NThresh?'],'!! Warning !!','Yes','No','Yes');
%         switch choice
%             case 'Yes'
%             prompt={'Enter value for Nthresh (Must be at least 2):'}
%             dlg_title='Nthresh Input'
%             answer=inputdlg(prompt,dlg_title)
%             Nthresh=str2num(answer{:});
%             Nthresh_check=(sum(piv.N(:)>=Nthresh)/numel(piv.N));
%             %Save choices for Nthresh (column 1) and the respecive percentatage (%) of small
%             %particles of that will used for pic in matrix using that Nthresh(column 2)
%             tmp=Nthresh;
%             tmp1=Nthresh_check;
%             piv_Nthresh=[tmp tmp1
%             piv_Nthresh(:,1) piv_Nthresh(:,2)];
%  
%              case 'No'
%               %Nthresh=Nthresh;
% 
%                   break
%         end
%         end
%     end
%     
%     piv.Nthresh=piv_Nthresh;
   %% 
   save(fnout,'piv','-v7')
   %create video of PIV results
   opts.fps=fps;
    video_piv_new(fnseq,piv,strrep(fnout,'.mat','.avi'),opts)
   %video_piv(fnseq,m,piv,strrep(fnout,'.mat','.avi'),opts)
end
